package com.kayak.test.api;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * @author xiaon
 * 去除配置了dubbo consumer但是有没有使用的配置
 * 
 */
public class CheckDubboConf extends TestBase{
	
	private URL path = CheckDubboConf.class.getResource("/");
	private String p = path.getPath().substring(0,path.getPath().indexOf("/kayak-butterfly-api/"));
	{ p = p+"\\kayak-butterfly-api\\src\\main\\env\\dev\\conf\\spring\\"; }
	
	String scankey = "com.kayak.easysp.";
	
	@org.junit.Test
	public void test(){
		Map<String, String> infmap = new HashMap<String, String>();
		System.out.println("-----------------------------------------------------");
		Map<String, String> flmap = getDubboConfigMap();
		Map<String, String> itmap = getDubboUsingConfigMap();
		System.out.println(flmap);
		System.out.println("-----------------------------------------------------");
		System.out.println(itmap);
		
		System.out.println("------------------结果--------------------------------");
		Iterator<String> it = flmap.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			if(itmap.containsKey(key)){
				
			}else{
				System.out.println(key);
				infmap.put(key, flmap.get(key));
			}
		}
		System.out.println("-----------------------------------------------------");
		
		//删除dubbo配置中多余的
		//moddubboconf(infmap);
		
	}
	
	public void moddubboconf(Map<String, String> infmap) { 
		try {  
        	File[] fs = new File(p).listFiles(new FilenameFilter(){
				@Override
				public boolean accept(File dir, String name) {
					if(name.startsWith("applicationConsumer") && name.endsWith(".xml")){
						return true;
					}
					return false;
				}});
        	
        	for(File f : fs){
	            //1。获取DOM 解析器的工厂实例。  
	            DocumentBuilderFactory factory  = DocumentBuilderFactory.newInstance();  
	            //2。获得具体的DOM解析器。  
	            DocumentBuilder builder = factory.newDocumentBuilder();  
	              
	            //3。获取文件  
	            Document document = builder.parse(f);  
	            
	            //4。获取根元素  
	            Element root = document.getDocumentElement();  
	            //5。获取根节点[有多个节点]  
	            NodeList list = root.getElementsByTagName("dubbo:reference");
	            List<Node> delist = new ArrayList<Node>();
	            for (int i = 0; i < list.getLength(); i++) {  
	                Node n = list.item(i);
	                NamedNodeMap nodemap = n.getAttributes();
	                
	                String inf = nodemap.getNamedItem("interface").getNodeValue();
	                if(infmap.containsKey(inf)){
	                	delist.add(n);
	                }
	            }  
	            
	            for(int i=0;i<delist.size();i++){
	            	root.removeChild(delist.get(i));
	            }
	            
                //定义了用于处理转换指令，以及执行从源到结果的转换的  
		        TransformerFactory transformerFactory = TransformerFactory.newInstance();  
		        Transformer transformer = transformerFactory.newTransformer();  
		        transformer.setOutputProperty("encoding", "UTF-8");  
		              
		        transformer.transform(new DOMSource(document), new StreamResult(f));     

        	}                         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}
	
    public Map<String, String> getDubboConfigMap() {  
    	Map<String, String> flmap = new HashMap<String, String>();
        try {  
        	File[] fs = new File(p).listFiles(new FilenameFilter(){
				@Override
				public boolean accept(File dir, String name) {
					if(name.startsWith("applicationConsumer") && name.endsWith(".xml")){
						return true;
					}
					return false;
				}});
        	
        	for(File f : fs){
	            //1。获取DOM 解析器的工厂实例。  
	            DocumentBuilderFactory factory  = DocumentBuilderFactory.newInstance();  
	            //2。获得具体的DOM解析器。  
	            DocumentBuilder builder = factory.newDocumentBuilder();  
	              
	            //3。获取文件  
	            Document document = builder.parse(f);  
	  
	            //4。获取根元素  
	            Element root = document.getDocumentElement();  
	            //5。获取根节点[有多个节点]  
	            NodeList list = root.getElementsByTagName("dubbo:reference");  
	            for (int i = 0; i < list.getLength(); i++) {  
	                Node n = list.item(i);
	                NamedNodeMap nodemap = n.getAttributes();
	                
	                flmap.put(nodemap.getNamedItem("interface").getNodeValue(), 
	                		nodemap.getNamedItem("id").getNodeValue());
	            }  
        	}                         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        
        return flmap;
    }  
    
    public Map<String, String> getDubboUsingConfigMap() {  
    	Map<String, String> itmap = new HashMap<String, String>();
    	String[] beannames= applicationContext.getBeanDefinitionNames();
		for(String s : beannames){
			Object t = applicationContext.getBean(s);
			if(t.getClass().getName().startsWith(scankey)){
				list(t.getClass(), itmap);
			}
		}
		return itmap;
	}
    
    private void list(Class cls, Map<String, String> itmap) {
    	Field[] fs = cls.getDeclaredFields();
		for(Field f : fs){
			if(f.getType()!=null){
				itmap.put(f.getType().getName(), f.getName());
			}
		}
		Class supcls = cls.getSuperclass();
		if(supcls!=null && !supcls.getName().equals("java.lang.Object")){
			list(supcls, itmap);
		}
	}

}
